package com.wiwf.model.task.thread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wiwf.model.task.service.TaskOutHandlerService;

/**
 * 任务消息输出处理器
 *
 * @author kehui
 */
public class OutHandlerThread extends Thread {
	
	Logger logger = LoggerFactory.getLogger(OutHandlerThread.class);

	/**控制状态 */
	private volatile boolean desstatus = true;
	
	/**读取输出流*/
	private BufferedReader br = null;
	
	/**任务ID*/
	private String id = null;
	
	/**消息处理方法*/
	private TaskOutHandlerService ohm;

	/**
	 * 创建输出线程（默认立即开启线程）
	 * @param is
	 * @param id
	 * @param ohm
	 * @return
	 */
	public static OutHandlerThread create(InputStream is, String id, TaskOutHandlerService ohm) {
		return create(is, id, ohm,true);
	}
	
	/**
	 * 创建输出线程
	 * @param is
	 * @param id
	 * @param ohm
	 * @param start-是否立即开启线程
	 * @return
	 */
	public static OutHandlerThread create(InputStream is, String id, TaskOutHandlerService ohm, boolean start) {
		OutHandlerThread out= new OutHandlerThread(is, id, ohm);
		if(start){ 
			out.start();
		}
		return out;
	}
	
	public void setOhm(TaskOutHandlerService ohm) {
		this.ohm = ohm;
	}
	
	public void setDesStatus(boolean desStatus) {
		this.desstatus = desStatus;
	}

	public void setId(String id) {
		this.id = id;
	}

	public TaskOutHandlerService getOhm() {
		return ohm;
	}

	public OutHandlerThread(InputStream is, String id, TaskOutHandlerService ohm) {
		br = new BufferedReader(new InputStreamReader(is));
		this.id = id;
		this.ohm=ohm;
	}

	/**
	 * 执行输出线程
	 */
	@Override
	public void run() {
		String msg = null;
		try {
			logger.info("{}：开始执行！",id);
			
			while (desstatus && (msg = br.readLine()) != null) {
				ohm.parse(id,msg);
				//
				// if(ohm.isbroken()) {System.err.println("检测到中断，提交重启任务给保活处理器");}
			}
		} catch (IOException e) {
			logger.info("{}：发生内部异常错误，自动关闭！",this.getId());
			setDesStatus(false);
		} finally {
			if (this.isAlive()) {
				setDesStatus(false);
			}
		}
	}

}
